<?php

$data = array();
$data['errors'] = array();

if (isset($_GET['book_id'])) {
    $data['book']['book_id'] = (int) ($_GET['book_id']);

    // Select data about the book: title, authors..
    $sql = 'SELECT b.book_title, a.author_id, a.author_name
            FROM books as b
            INNER JOIN books_authors as ba ON ba.book_id = b.book_id
            INNER JOIN authors as a ON a.author_id = ba.author_id
            WHERE b.book_id = ' . $data['book']['book_id'] .
            ' ORDER BY a.author_name ASC';
    $query = mysqli_query($connection, $sql);

    if (mysqli_num_rows($query) > 0) {
        while ($row = mysqli_fetch_assoc($query)) {
            $data['book']['book_title'] = $row['book_title'];
            $authors = array();
            $authors['id'] = $row['author_id'];
            $authors['name'] = $row['author_name'];
            $data['book']['authors'][] = $authors;
        }

        // Insert new comment
        if (isset($_POST['bookComment'])) {
            $bookComment_esc = mysqli_real_escape_string($connection, trim($_POST['bookComment']));
            $sql = 'INSERT INTO comments (user_id, book_id, content, creation_date) VALUES (' . $_SESSION['user_id'] . ', '
                    . $data['book']['book_id'] . ', "' . $bookComment_esc . '", "' . date('Y-m-d h:i:s') . '")';
            mysqli_query($connection, $sql);
        }

        // Select data about comments
        $sql = 'SELECT c.content, c.user_id, u.username, c.creation_date
                FROM comments as c
                INNER JOIN users as u ON c.user_id = u.user_id
                WHERE c.book_id = ' . $data['book']['book_id'] .
                ' ORDER BY c.creation_date DESC';
        $query = mysqli_query($connection, $sql);

        $data['book']['comments'] = array();
        $comment = array();
        while ($row = mysqli_fetch_assoc($query)) {            
            $comment['user_id'] = $row['user_id'];
            $comment['username'] = $row['username'];
            $comment['creation_date'] = $row['creation_date'];
            $comment['content'] = $row['content'];
            $data['book']['comments'][] = $comment;
        }
    } else {
        $data['errors'][] = 'Тази книга не e намерена';
    }
} else {
    header('Location: index.php');
    exit();
}

$data['title'] = 'Книга';
render($data, 'templates/book_public.php');